<template>
    <div>
        <basic-container>
            <el-form ref="formSearch" :model="formSearch" label-width="100px" size="small" :inline="true">
                <el-col :span='24'>
                    <el-form-item label="项目状态:">
                        <el-select v-model="formSearch.status" placeholder="项目状态" style='width:100px'>
                            <el-option label="全部" :value="-1"></el-option>
                            <el-option  v-for='v in itemsTatus' :key='v.id' :label="v.name" :value='v.id' ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="项目编号">
                        <el-input v-model="formSearch.number" placeholder="请输入项目编号"></el-input>
                    </el-form-item>
                    <el-form-item label="项目名称">
                        <el-input v-model="formSearch.name" placeholder="请输入项目名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchFormSubmit()">搜索</el-button>
                    </el-form-item>
                </el-col> 
                <el-col :span='24' >
                    <el-form-item>
                        <el-button type="primary" size="small" @click.stop="handleAdd()">添加</el-button>
                    </el-form-item>
                </el-col>
            </el-form>
            <!-- 表格 -->
            <avue-crud :option="tableOption" :data="tableData" :table-loading="tableLoading" :page="page" ref="crud" @current-change='currentPage'  @size-change="sizeChange">
                 <template slot-scope="scope" slot="progectData">
                     {{scope.row.startTime}}<span> 至 </span>{{scope.row.endTime}}
                </template>
                <template slot-scope="scope" slot="menu">
                    <el-button type="primary" size="small"  plain @click.stop="handleEdit(scope.row,scope.index)">修改</el-button>
                    <el-button type="primary" size="small"  plain @click.stop="handleDelete(scope.row,scope.index)">删除</el-button>
                    <el-button type="primary" size="small"  plain @click.stop="handleManage(scope.row,scope.index)">台账管理</el-button>
                </template>
            </avue-crud>
        </basic-container>
        <!-- 修改/新增-->
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="30%" class="diading" :before-close="dialogFormVisibleClass">
            <el-form ref="dialogForm"  :model="dialogForm" :rules="rules"    label-position="left" label-width="100px"  >
                <el-form-item label="项目编号：" prop='number'>
                    <el-input v-model="dialogForm.number" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="项目名称：" prop='name'>
                    <el-input v-model="dialogForm.name" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label=" 项目时间:" prop='progectData'>
                    <el-date-picker format="yyyy-MM-dd"  v-model="dialogForm.progectData" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style='width:100%'>
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="项目说明：" prop='description'>
                    <el-input v-model="dialogForm.description"  type="textarea" :autosize='{ minRows: 3, maxRows: 6}' placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="项目状态：" prop='status'>
                    <el-radio-group v-model="dialogForm.status">
                        <el-radio  v-for='v in itemsTatus' :key='v.id' :label="v.id" :value='v.id'>{{v.name}}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align:center">
                <el-button  size="small" @click="dialogFormVisible=false;handleAddLineExit('dialogForm')">关 闭</el-button>
                <el-button  size="small" type="primary" @click="handleAddLine('dialogForm')">确 认</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { listOption } from "@/const-personal/projectManage/progectList.js"
    import { getListOfSearch,getDataById,insertEntity,updateEntity,deleteEntity } from "@/api/progec/progectList"
    import { validatenull } from '@/util/validate'
    import { formatDate, deepClone } from '@/util/util'
    import { setStore } from '@/util/store'
    export default {
        name: "progectList",
         data() {
             var validateProgectData = (rule, value, callback) => {
                 if (value.length!=2) {
                     callback(new Error('请选择项目时间'));
                 } else {
                     callback();
                 }
             };
            return {
                formSearch : {
                    status: -1,
                    name:'',
                    number:'',
                    description:''
                },
                tableOption:listOption,
                tableData:[{id:0,status:2},{id:2,status:1}],//数据
                page: {
                    total: 10, //总页数
                    currentPage: 1, //当前页数
                    pageSize: 5, //每页显示多少条
                    pageSizes:[5,10,20]
                },
                tableLoading:false,
                itemsTatus:[//项目状态
                    {id:0,name:'待启动'},
                    {id:1,name:'已启动'},
                    {id:2,name:'已结束'}
                ],
                 // 修改/新增
                dialogTitle:'人员添加',
                dialogFormVisible:false,
                dialogForm:{
                    id:null,
                    name:'',
                    number:'',
                    description:'',
                    status:'',
                    progectData:[]
                },
                rules:{
                    number:[{required: true,message: '项目编号不能为空',trigger: 'blur'},{ max: 50, message: '输入的长度请在 50 个字符', trigger: 'blur'}],
                    name:[{required: true,message: '项目姓名不能为空',trigger: 'blur'},{ max: 50, message: '输入的长度请在 50 个字符', trigger: 'blur'}],
                    description:[{required: true,message: '项目说明不能为空',trigger: 'blur'},{ max: 200, message: '输入的长度请在 200 个字符', trigger: 'blur'}],
                    progectData:[{required: true,validator: validateProgectData,trigger: 'blur'}],
                    status:[{required: true,message: '请选择项目状态',trigger: 'change'}],
                },
            }
        },
        created () {
            this.searchFormSubmit()
        },
        methods:{
            // 点击搜索
            searchFormSubmit(){
                this.tableLoading = true;
                let data = {
                    status: this.formSearch.status,
                    name: this.formSearch.name,
                    number: this.formSearch.number,
                    description: this.formSearch.description
                }
                data.page = this.page.currentPage;
                data.size = this.page.pageSize;
                if(this.formSearch.status==-1){
                    data.status = null
                }
                getListOfSearch(data).then(res => {
                    if(res.data.code==200){
                        this.tableData = res.data.data.list;
                        this.page.total = res.data.data.total;
                        this.page.currentPage = res.data.data.pageNum;
                        this.page.pageSize = res.data.data.pageSize;
                    } else {
                        this.$notify.error({ title: '查询失败', message: '获取项目列表失败！', type: 'danger', });
                    }
                })

                this.tableLoading = false;
            },
            // 点击重置
            handleReset(){},
            // 切换分页
            currentPage(val){
                this.page.currentPage = val;
                this.searchFormSubmit();
            },
            //分页大小
            sizeChange(val){
                this.page.pageSize = val;
                this.searchFormSubmit();
            },
            handleAdd(){
                this.dialogFormVisible= true;
                this.dialogTitle='添加项目';
                this.dialogForm={number:'',name:'',description:'',progectData:'',status:'',id:null}
            },
            handleAddLineExit(dialogForm){
                this.$refs[dialogForm].resetFields();
            },
            // 修改
            handleEdit(row,index){
                this.dialogFormVisible = true;
                this.dialogTitle='修改项目';
                getDataById({id:row.id}).then(res =>{
                    if(res.data.code==200){
                        this.dialogForm.id = res.data.data.id;
                        this.dialogForm.status = res.data.data.status;
                        this.dialogForm.name = res.data.data.name;
                        this.dialogForm.number = res.data.data.number;
                        this.dialogForm.description = res.data.data.description;
                        this.dialogForm.progectData = [new Date(res.data.data.startTime),new Date(res.data.data.endTime)];
                    } else {
                        this.$notify.error({ title: '操作失败', message: '获取项目信息失败！', type: 'danger', });
                    }
                })
            },
            // 删除
            handleDelete(row,index){
                this.$confirm('删除后，项目（'+ row.name +'）将无法找回, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //请求-删除
                    deleteEntity({id: row.id}).then(res => {
                        if(res.data.code==200){
                            this.$notify({ title: '操作成功', type: 'success', message: '已成功删除项目（'+row.name+'）!'});
                            this.dialogFormVisible = false;
                            this.searchFormSubmit()
                        } else {
                            this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                        }
                    })
                }).catch(() => {
                    this.$notify({ title: '已取消删除', type: 'info', });
                });
            },
            // 确认新增/修改
            handleAddLine(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let data = {
                            startTime : formatDate(this.dialogForm.progectData[0],'yyyy-MM-dd'),
                            endTime : formatDate(this.dialogForm.progectData[1],'yyyy-MM-dd'),
                            description : this.dialogForm.description,
                            number : this.dialogForm.number,
                            name : this.dialogForm.name,
                            status : this.dialogForm.status,
                            id : this.dialogForm.id
                        };
                        //添加
                         if(validatenull(data.id)){
                            insertEntity(data).then(res => {
                                if(res.data.code==200){
                                    this.$notify({ title: '操作成功', type: 'success', message: '已成功添加项目（'+this.dialogForm.name+'）!'});
                                    this.dialogFormVisible = false;
                                    this.handleAddLineExit('dialogForm')
                                    this.searchFormSubmit()
                                } else {
                                    this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                                }
                            })
                        } else {
                            updateEntity(data).then(res => {
                                if(res.data.code==200){
                                    this.$notify({ title: '操作成功', type: 'success', message: '已成功修改项目（'+this.dialogForm.name+'）!'});
                                    this.dialogFormVisible = false;
                                    this.handleAddLineExit('dialogForm')
                                    this.searchFormSubmit()
                                } else {
                                    this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                                }
                            })
                        }
                    }
                })
            },
            //弹框关闭时
            dialogFormVisibleClass(){
                this.dialogFormVisible = false;
                this.handleAddLineExit('dialogForm')
            },
            // 台账管理
            handleManage(row,index){
                setStore({ name: 'projectId', content: row.id, type: 'session' })
                this.$router.push({ path: '/ledger/ProjectLedger' });
            },
        }
    }
</script>

<style >
.diading .el-dialog{
    min-width: 460px
}
</style>